package com.konsung.ksdc.common.mqtt;

import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.config.NetConfig;

/**
 * 创建者     kgh
 * 创建时间   2016/5/11 16:52
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class KsdcMqttClient extends MqttClient {
    // 消息质量 保证接收
    public static final int QOS_AR = 2; // always received

    // 服务端连接串
//    public static String CONNECTION_STRING = "tcp://" + NetConfig.mqttSserverIp + ":1883";
    public static String connectionString = "tcp://" + NetConfig.mqttSserverIp + ":1883";
    // 是否保留离线消息
    private final static boolean CLEAN_START = false;
    // 链接超时
    private final static short CONN_TIMEOUT = 5;
    // 主题消息优先级，必须与主题数量一致
    private int[] qosValue;

    // 客户端ID
    private String clientId;

    // 需要订阅的主题
    private String[] topics;

    // mqtt消息处理器
    private MqttMessageDispatcher messageDiapatcher = new MqttMessageDispatcher();

    /**
     * 构造方法
     * @param clientId 客服端id
     * @param topics 数组
     * @throws MqttException 通讯异常
     */
    public KsdcMqttClient(String clientId, String[] topics) throws MqttException {
        super(connectionString);
        //初始化消息质量，一般为2
        initQos(topics);
        this.clientId = clientId;
        this.topics = topics;

        // 注册回调
        super.registerSimpleHandler(messageDiapatcher);

        // 创建MQTT链接
        super.connect(this.clientId, CLEAN_START, CONN_TIMEOUT);

        // 订阅主题
        super.subscribe(this.topics, qosValue);
    }

    /**
     * 初始化消息质量
     * @param topics 数组数据
     */
    private void initQos(String[] topics) {
        this.qosValue = new int[topics.length];
        for (int i = 0; i < this.qosValue.length; i++) {
            this.qosValue[i] = QOS_AR;
        }
    }

    /**
     * 发送消息
     * @param userId 用户ID
     * @param mqttMsg 消息体
     * @throws Exception 异常信息
     */
    public void publish(String userId, MqttMsgBean mqttMsg) throws Exception {
        messageDiapatcher.publish(this, userId, mqttMsg);
    }
}
